// pages/discover/discover.js
const discoverService = require('../../services/discoverService');
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    activeTab: 'square',
    loading: false,
    loadingMore: false,
    
    // 搜索
    keyword: '',
    showSearch: false,
    
    // 数据列表
    kitchens: [],
    dishes: [],
    
    // 分页参数
    pageSize: 10,
    currentKitchenPage: 0,
    currentDishPage: 0,
    hasMoreKitchens: true,
    hasMoreDishes: true,
    currentPage: 1,
    topicGroups: [], // 专题分组数据
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // 每次显示页面时刷新数据
    this.refreshData();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.setData({
      currentPage: 1,
      hasMoreDishes: true
    });
    this.loadData();
    wx.stopPullDownRefresh();
  },

  /**
   * 刷新数据
   * @param {Function} callback 刷新完成后的回调函数
   */
  refreshData: function(callback) {
    // 重置分页参数
    this.setData({
      currentKitchenPage: 0,
      currentDishPage: 0,
      hasMoreKitchens: true,
      hasMoreDishes: true,
      kitchens: [],
      dishes: []
    });

    // 加载新数据
    this.loadData().then(() => {
      if (callback) callback();
    });
  },

  /**
   * 切换标签页
   */
  switchTab: function(e) {
    const tab = e.currentTarget.dataset.tab;
    if (tab === this.data.activeTab) return;
    
    this.setData({ 
      activeTab: tab,
      currentPage: 1
    });

    if (tab === 'topic') {
      this.loadTopicKitchens();
    } else if (tab === 'square') {
      this.loadDishes();
    }
  },

  /**
   * 切换分类
   */
  switchCategory: function(e) {
    const category = e.currentTarget.dataset.category;
    this.setData({
      activeCategory: category,
      dishes: [],
      currentDishPage: 0,
      hasMoreDishes: true
    });
    
    // 重新加载菜品数据
    this.loadDishes();
  },
  
  /**
   * 加载数据
   */
  loadData: async function() {
    if (this.data.activeTab === 'square') {
      return this.loadDishes();
    } else if (this.data.activeTab === 'topic') {
      return this.loadTopicKitchens();
    }
  },
  
  /**
   * 加载厨房数据
   */
  loadKitchens: async function() {
    if (!this.data.hasMoreKitchens || this.data.loading) return;
    
    this.setData({ loading: true });
    
    try {
      const { pageSize, currentKitchenPage, keyword } = this.data;
      
      const kitchens = await discoverService.getSharedKitchens({
        keyword,
        limit: pageSize,
        skip: currentKitchenPage * pageSize
      });
      
      // 合并数据
      const newKitchens = currentKitchenPage === 0 ? kitchens : [...this.data.kitchens, ...kitchens];
      
      this.setData({
        kitchens: newKitchens,
        currentKitchenPage: currentKitchenPage + 1,
        hasMoreKitchens: kitchens.length === pageSize,
        loading: false
      });
    } catch (err) {
      console.error('加载厨房数据失败', err);
      this.setData({ loading: false });
      
      wx.showToast({
        title: '加载数据失败',
        icon: 'none'
      });
    }
  },
  
  /**
   * 加载菜品数据
   */
  loadDishes: async function() {
    if (!this.data.hasMoreDishes || this.data.loadingMore) return;
    
    this.setData({ loadingMore: true });
    
    try {
      const { pageSize, currentDishPage, keyword, activeCategory } = this.data;
      
      const dishes = await discoverService.getSharedDishes({
        category: activeCategory,
        keyword,
        limit: pageSize,
        skip: currentDishPage * pageSize
      });
      dishes.forEach(dish => {
        dish.isLiked = dish.likeCount > 0;
      });
      // 合并数据
      const newDishes = currentDishPage === 0 ? dishes : [...this.data.dishes, ...dishes];
      
      this.setData({
        dishes: newDishes,
        currentDishPage: currentDishPage + 1,
        hasMoreDishes: dishes.length === pageSize,
        loadingMore: false
      });
    } catch (err) {
      console.error('加载菜品数据失败', err);
      this.setData({ loadingMore: false });
      
      wx.showToast({
        title: '加载数据失败',
        icon: 'none'
      });
    }
  },
  
  /**
   * 显示搜索框
   */
  showSearch: function() {
    this.setData({ showSearch: true });
  },
  
  /**
   * 关闭搜索框
   */
  hideSearch: function() {
    this.setData({ showSearch: false });
  },
  
  /**
   * 输入搜索关键词
   */
  onSearchInput: function(e) {
    this.setData({ keyword: e.detail.value });
  },
  
  /**
   * 执行搜索
   */
  onSearch: function() {
    // 重置数据
    this.setData({
      kitchens: [],
      dishes: [],
      currentKitchenPage: 0,
      currentDishPage: 0,
      hasMoreKitchens: true,
      hasMoreDishes: true
    });
    
    // 重新加载数据
    this.loadData();
    
    // 关闭搜索框
    this.hideSearch();
  },
  
  /**
   * 点赞菜品
   */
  likeDish: function(e) {
    const dishId = e.currentTarget.dataset.id;
    const index = e.currentTarget.dataset.index;
    const kitchenId = e.currentTarget.dataset.kitchenid;
    discoverService.likeDish(dishId, kitchenId).then(liked => {
      if (liked !== null) {
        // 更新点赞状态和数量
        const newDishes = [...this.data.dishes];
        newDishes[index].isLiked = liked;
        newDishes[index].likeCount = liked 
          ? (newDishes[index].likeCount || 0) + 1 
          : Math.max((newDishes[index].likeCount || 1) - 1, 0);
        
        this.setData({ dishes: newDishes });
        
        wx.showToast({
          title: liked ? '已点赞' : '已取消点赞',
          icon: 'success'
        });
      }
    });
  },
  
  /**
   * 收藏菜品
   */
  favoriteDish: function(e) {
    const dishId = e.currentTarget.dataset.id;
    const kitchenId = e.currentTarget.dataset.kitchenid;
    const index = e.currentTarget.dataset.index;
    
    discoverService.favoriteDish(dishId, kitchenId).then(favorited => {
      if (favorited !== null) {
        // 更新收藏状态
        const newDishes = [...this.data.dishes];
        newDishes[index].isFavorited = favorited;
        
        this.setData({ dishes: newDishes });
        
        wx.showToast({
          title: favorited ? '已收藏' : '已取消收藏',
          icon: 'success'
        });
      }
    });
  },
  
  /**
   * 跳转到菜品详情页
   */
  navigateToDishDetail(e) {
    const { id, kitchenid } = e.currentTarget.dataset;
    if (!id) {
      wx.showToast({
        title: '菜品信息不完整',
        icon: 'none'
      });
      return;
    }
    
    console.log('跳转参数：', { id, kitchenid }); // 添加日志
    
    let url = '../dish-detail/dish-detail?dishId=' + id + '&from=discover'; // 添加 from=discover
    if (kitchenid) {
      url += '&kitchenId=' + kitchenid; // 保留 kitchenId (如果存在)
    }

    wx.navigateTo({
      url: url, // 使用拼接好的 url
      fail: (err) => {
        console.error('跳转失败', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },
  
  /**
   * 跳转到分享厨房页
   */
  navigateToKitchenDetail: function(e) {
    const kitchenId = e.currentTarget.dataset.id;
    
    // 检查厨房ID是否存在
    if (!kitchenId) {
      wx.showToast({
        title: '厨房信息不完整',
        icon: 'none'
      });
      return;
    }

    console.log('准备跳转到分享厨房页，ID:', kitchenId);
    
    // 跳转到分享厨房页面
    wx.navigateTo({
      url: `/pages/kitchen-shared/kitchen-shared?id=${kitchenId}`,
      success: () => {
        console.log('跳转到分享厨房页成功');
      },
      fail: (err) => {
        console.error('跳转到分享厨房页失败:', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 初始化加载数据
    this.loadData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // 根据当前标签页加载更多数据
    if (this.data.activeTab === 'square') {
      this.loadDishes();
    } else if (this.data.activeTab === 'topic') {
      this.loadKitchens();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '发现美食',
      path: '/pages/discover/discover'
    };
  },

  /**
   * 加载专题厨房数据
   */
  async loadTopicKitchens() {
    try {
      this.setData({ loading: true });
      
      const db = wx.cloud.database();
      /**
       *  // 从 Share 表中查询所有记录
      const { data: allshares } = await db.collection('Share').get();
       // 筛选出厨房记录和菜品记录
       const kitchenRecords = allshares.filter(record => record.type === 'topic');
       const dishRecords = allshares.filter(record => record.type === 'dish');

       // 遍历每个厨房记录
       for (const kitchen of kitchenRecords) {
           let totalLikeCount = 0;
           let totalCommentCount = 0;

           // 找出属于该厨房的所有菜品记录
           const kitchenDishes = dishRecords.filter(dish => dish.kitchenId === kitchen.kitchenId);

           // 计算该厨房下所有菜品的 likeCount 和 commentCount 总和
           kitchenDishes.forEach(dish => {
               totalLikeCount += dish.likeCount || 0;
               totalCommentCount += dish.commentCount || 0;
           });

           // 更新该厨房记录的 likeCount 和 commentCount
           await db.collection('Share').doc(kitchen._id).update({
               data: {
                   likeCount: totalLikeCount,
                   commentCount: totalCommentCount
               }
           });
       }
       */
      // 获取所有分享到专题的厨房
      const { data: shares } = await db.collection('Share')
      .where({
        type: 'topic'
      })
      .orderBy('shareTime', 'desc')
      .get();
      // 按标签分组处理数据
      const groupedData = {};
      shares.forEach(share => {
        const tags = share.tags && share.tags.length > 0 ? share.tags : ['分享厨房'];
        tags.forEach(tag => {
          if (!groupedData[tag]) {
            groupedData[tag] = [];
          }
          // 确保不重复添加同一个厨房
          if (!groupedData[tag].some(k => k.kitchenId === share.kitchenId)) {
            groupedData[tag].push(share);
          }
        });
      });

      // 转换为数组格式并按厨房数量排序
      const topicGroups = Object.entries(groupedData)
        .map(([tag, kitchens]) => ({
          tag,
          kitchens
        }))
        .sort((a, b) => b.kitchens.length - a.kitchens.length);

      this.setData({
        topicGroups,
        loading: false
      });
    } catch (error) {
      console.error('加载专题厨房失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },
}); 